package conf

import (
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/mitchellh/mapstructure"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

func MustLoad(f string, c interface{}) {
	err := Load(f, c)
	if err != nil {
		log.Fatal(err)
	}

}

// Setup initialize the configuration instance
func Load(f string, c interface{}) error {
	v := viper.New()
	v.SetConfigFile(f)
	content, err := ioutil.ReadFile(f)
	if err != nil {
		return errors.Wrap(err, "read conf err")
	}

	//Replace environment variables
	err = v.ReadConfig(strings.NewReader(os.ExpandEnv(string(content))))
	if err != nil {
		return errors.Wrap(err, "vip read conf err")
	}

	optDecode := viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
		mapstructure.StringToTimeDurationHookFunc(),
	))

	if err := v.Unmarshal(&c, optDecode); err != nil {
		return errors.Wrap(err, "viper Unmarshal error")
	}
	return nil

}
